import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class ImageBinarizationWithColorRange {

    public static BufferedImage binarize(BufferedImage image, int threshold, int[] colorLowerBound, int[] colorUpperBound, boolean setToBlack) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage binaryImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int argb = image.getRGB(x, y);
                int alpha = (argb >> 24) & 0xff;
                int red = (argb >> 16) & 0xff;
                int green = (argb >> 8) & 0xff;
                int blue = argb & 0xff;

                // 判断当前像素颜色是否在指定的颜色范围内
                boolean inColorRange = red >= colorLowerBound[0] && red <= colorUpperBound[0] &&
                        green >= colorLowerBound[1] && green <= colorUpperBound[1] &&
                        blue >= colorLowerBound[2] && blue <= colorUpperBound[2];

                if (inColorRange) {
                    if (setToBlack) {
                        binaryImage.setRGB(x, y, 0xFF000000);
                    } else {
                        binaryImage.setRGB(x, y, 0xFFFFFFFF);
                    }
                } else {
                    int gray = (int)(0.299 * red + 0.587 * green + 0.114 * blue);
                    int newPixel = gray > threshold? 0xFFFFFFFF : 0xFF000000;
                    binaryImage.setRGB(x, y, newPixel);
                }
            }
        }

        return binaryImage;
    }

    public static void main(String[] args) {
        try {
            File inputFile = new File("src\\main\\resources\\tess4j\\split\\11.png");
            BufferedImage originalImage = ImageIO.read(inputFile);

            // 定义颜色范围的下限和上限，这里以#F8F5A5为例，可根据实际情况调整
            int[] colorLowerBound = {248, 245, 165};
            int[] colorUpperBound = {248, 245, 165};

            // 设置是否将颜色范围内的像素设为黑色，这里设为true，可根据需求调整
            boolean setToBlack = true;

            // 阈值范围 [0, 255]
            for (int threshold = 0; threshold < 255; threshold++) {
//                int threshold = 128; // 阈值，可以根据实际情况调整
                BufferedImage binaryImage = binarize(originalImage, threshold, colorLowerBound, colorUpperBound, setToBlack);
                File output = new File(inputFile.getParentFile() + "\\33\\二值化\\" + threshold + ".jpg");
                ImageIO.write(binaryImage, "jpg", output);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}